package jsc.graph;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JLabel;
import javax.swing.JFileChooser;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.filechooser.FileFilter;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.awt.BorderLayout;

import jsc.acid.Dictionary;
import jsc.acid.SpellChecker;
import jsc.acid.Text;
import jsc.acid.Word;

/**
 * This is the main class of the graphic interface
 * 
 * @author Alec Ermis, Maxime Rihouey
 *
 */

public class MainFrame {

	private JFrame frame;
	private FrameWrongWords frameWrongWords;
	private FrameDictionary frameDictionaries;
	private JLabel statusbar;
	private JTextPane tpTexteAcorriger;
	private SpellChecker JSP;
	private JMenuItem openText;
	private JMenuItem btnAddDictionary;
	private boolean useABR;

	/**
	 * Create the application.
	 */
	public MainFrame(boolean useABR) {
		this.useABR = useABR;
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 800, 600);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setTitle("Java Spell Checker");
		frame.getContentPane().setLayout(new BorderLayout(0, 0));
		frame.setVisible(true);

		frameDictionaries = new FrameDictionary();

		JButton btnCorriger = new JButton("Corriger");
		frame.getContentPane().add(btnCorriger, BorderLayout.SOUTH);

		btnCorriger.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(JSP != null){

					// on repart de zero
					JSP.updateText(tpTexteAcorriger.getText());
					if(frameWrongWords != null) frameWrongWords.setVisible(false);
					frameWrongWords = new FrameWrongWords();
					frameWrongWords.setVisible(true);
					HashMap<Word, HashSet<String>> alternatives = JSP.correct();
					for(Word word : alternatives.keySet()){
						frameWrongWords.add(word, alternatives.get(word));
					}
				}
			}
		});

		statusbar = new JLabel("Choisissez un fichier à corriger (File > Charger text) puis ajoutez un ou plusieurs dictionnaire(s) (File > Ajouter Dictionnaire).");
		frame.getContentPane().add(statusbar, BorderLayout.NORTH);

		tpTexteAcorriger = new JTextPane();
		tpTexteAcorriger.setEditable(true);

		frame.getContentPane().add(tpTexteAcorriger, BorderLayout.CENTER);

		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);

		JMenu mnFichier = new JMenu("Fichier");
		menuBar.add(mnFichier);

		openText = new JMenuItem("Charger Texte");
		mnFichier.add(openText);
		openText.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {

				// the dictionaries are supposed to be in the directory "texts/" so we open the file chooser at this directory
				File dictsDirectory =  new File("texts/");
				JFileChooser chooser;
				if(dictsDirectory.isDirectory()){
					chooser = new JFileChooser(dictsDirectory);
				}else{
					chooser = new JFileChooser();
				}
				chooser.setFileFilter(new FileFilter() {

					@Override
					public String getDescription() {
						// TODO Auto-generated method stub
						return null;
					}

					@Override
					public boolean accept(File f) {
						if(f.getName().endsWith(".txt") || f.isDirectory()) return true;
						return false;
					}
				});
				chooser.setMultiSelectionEnabled(false);
				int option = chooser.showOpenDialog(new JFileChooser());

				if (option == JFileChooser.APPROVE_OPTION) {
					File sf = chooser.getSelectedFile();
					statusbar.setText("Vous avez choisi " + sf.getPath() + " : ");

					// ajout du text
					try {
						JSP = new SpellChecker(new Text(new File(sf.getPath())));
						tpTexteAcorriger.setText(JSP.getText().toString());
						btnAddDictionary.setVisible(true);
					} catch (IOException e) {
						statusbar.setText("Ce fichier n'existe pas.");
					}
				}
				else {
					statusbar.setText("Vous avez annulé. Choisissez un fichier à corriger (File > Charger text) puis corrigez-le (Corriger).");
				}
				if(JSP != null){
					openText.setVisible(false);
				}
			}
		});

		btnAddDictionary = new JMenuItem("Ajouter Dictionnaire");
		mnFichier.add(btnAddDictionary);
		btnAddDictionary.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent ae) {

				// the dictionaries are supposed to be in the directory "dicts/" so we open the file chooser at this directory
				File dictsDirectory =  new File("dicts/");
				JFileChooser chooser;
				if(dictsDirectory.isDirectory()){
					chooser = new JFileChooser(dictsDirectory);
				}else{
					chooser = new JFileChooser();
				}
				chooser.setFileFilter(new FileFilter() {

					@Override
					public String getDescription() {
						// TODO Auto-generated method stub
						return null;
					}

					@Override
					public boolean accept(File f) {
						if(f.getName().endsWith(".jsc") || f.isDirectory()) return true;
						return false;
					}
				});
				chooser.setMultiSelectionEnabled(true);
				int option = chooser.showOpenDialog(new JFileChooser());

				if (option == JFileChooser.APPROVE_OPTION) {
					File[] sf = chooser.getSelectedFiles();
					for (int i = 0; i < sf.length; i++) {
						try {
							Dictionary dico = new Dictionary(sf[i], useABR);
							JSP.addDictionary(dico);
							frameDictionaries.add(dico);
							statusbar.setText(dico.getName()+" chargé.");
							frameDictionaries.setVisible(true);
						} catch (IOException e) {
							statusbar.setText("Ce fichier n'existe pas.");
						}
					}
				}
				else {
					statusbar.setText("Vous avez annulé. Choisissez un fichier à corriger (File > Ajouter dictionnaire) puis corrigez-le (Corriger).");
				}

			}
		});
		btnAddDictionary.setVisible(false);

	}

	/*
	 * Test
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				MainFrame main = new MainFrame(true);
			}
		});

	}

}
